<template>
  <AuFormModal
    ref="formRef"
    v-model="showModal"
    :title="title"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 600
    }"
    :formProps="{
      class: '!w-[546px]'
    }"
    @handleConfirm="handleConfirm"
  >
    <template #post_behind>
      <vxe-card class="w-full mt-2 py-[8px] h-[330px]" :padding="false">
        <el-tree-v2
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          :default-expanded-keys="expandedKeys"
          :item-size="38"
          show-checkbox
          :height="320"
        >
          <template #default="{ node }">
            <span class="el-tree-node__label">{{
              te(node.label) ? t(node.label) : node.label
            }}</span>
          </template>
        </el-tree-v2>
      </vxe-card>
    </template>
  </AuFormModal>
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import {
  AccountProp,
  postAdd,
  PostProp,
  postUpd
} from "@/api/teaInfuser/account";
import { computed, nextTick, ref, watch } from "vue";
import { BaseProps, inputProps } from "@/components/AuForm/type";
import { ElMessage, ElTreeV2 } from "element-plus";
import { TreeProp } from "@/api/teaInfuser/formula";
import type { TreeKey } from "element-plus/es/components/tree-v2/src/types";
import { isBoolean, storageLocal } from "@pureadmin/utils";
import { useI18n } from "vue-i18n";
import { pick } from "lodash-unified";
import { getAsyncRoutes } from "@/api/routes";
import { responsiveStorageNameSpace } from "@/config";
import { userKey } from "@/utils/auth";

interface Props {
  modelValue: boolean;
  formData?: Partial<PostProp>;
}

const { te, t } = useI18n();

const props = withDefaults(defineProps<Props>(), {
  modelValue: false
});
const emit = defineEmits(["update:modelValue", "submit"]);

const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(val: boolean) {
    emit("update:modelValue", val);
  }
});
const title = ref(t("role_manage.form.add_post_title"));
const selfFormData = ref({});
const formList = ref<[inputProps, inputProps, BaseProps]>([
  {
    type: "input",
    key: "name",
    label: "role_manage.form.post_name",
    placeholder: "role_manage.form.post_name_placeholder",
    required: true
  },
  {
    type: "input",
    key: "note",
    label: "table.note",
    inType: "textarea",
    rows: 3,
    placeholder: "role_manage.form.note_placeholder"
  },
  {
    type: "null",
    key: "post",
    label: "role_manage.form.permission_settings",
    slot: true
  }
]);
const formRef = ref();

const treeData = ref<TreeProp[]>([]);
const expandedKeys = ref<TreeKey[]>([]);
const treeProps = {
  value: "name",
  label: "title",
  class: "custom-node",
  children: "children"
};
const treeRef = ref();

const getTreeData = async () => {
  // const tree = storageLocal().getItem("async-routes") as any[];
  const type = storageLocal().getItem<{ type: string }>(
    `${responsiveStorageNameSpace()}system`
  )?.type as string;
  const userType = storageLocal().getItem<{ type: string }>(userKey)?.type;
  const tree = await getAsyncRoutes({ type, userType });
  const treeList = [];

  function treeEventLoop(arr: any[], treeList: any[]) {
    arr.forEach((item, i) => {
      // if (!isBoolean(item.meta.showLink)) {
      item.title = item?.meta?.title;
      treeList.push({
        ...item,
        title: item?.meta?.title,
        children: []
      });
      // }

      if (item.children) {
        expandedKeys.value.push(item.name);
        treeEventLoop(item.children, treeList[i]?.children);
      }
    });
  }

  treeEventLoop(tree.data, treeList);
  treeData.value = treeList;
  treeRef.value!?.setExpandedKeys(expandedKeys.value);
};

const setSelected = (data: PostProp) => {
  const { power_list } = data;
  if (power_list) {
    const tree = JSON.parse(power_list);
    treeRef.value!?.setCheckedKeys(tree);
  } else {
    treeRef.value!?.setCheckedKeys([]);
  }
};

const handleConfirm = (data: { id?: string; name: string; note: string }) => {
  let service = data.id ? postUpd : postAdd;
  const power_list = treeRef.value!?.getCheckedKeys();
  const pickData = pick(data, ["id", "name", "note"]);
  const param = {
    ...pickData,
    type: 1, // 只有商家
    power_list: JSON.stringify(power_list)
  };
  service(param).then(res => {
    if (res.code === 200) {
      emit("submit", res.data);
      ElMessage.success(
        t(
          data.id
            ? "role_manage.form.edit_success"
            : "role_manage.form.add_success"
        )
      );
      showModal.value = false;
    }
  });
};

watch(
  () => [showModal.value, props.formData],
  ([val, row]: [boolean, PostProp]) => {
    if (val) {
      title.value = row?.id
        ? t("role_manage.form.edit_post_title")
        : t("role_manage.form.add_post_title");

      nextTick(async () => {
        await getTreeData();
        setSelected(row);
        formRef.value.setFormData(row);
      });
    } else {
      formRef.value.reset();
    }
  }
);
</script>
